package com.dcy.auth.biz.service;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.dcy.auth.api.AuthApi;
import com.dcy.common.model.LoginAccount;
import com.dcy.common.constant.Constant;
import com.dcy.system.api.api.UserApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.Set;

/**
 * @Author：dcy
 * @Description:
 * @Date: 2021/4/15 9:29
 */
@DubboService(version = "1.0.0", timeout = 3000, interfaceClass = AuthApi.class)
public class AuthService implements AuthApi {

    @DubboReference(version = "1.0.0", check = false)
    private UserApi userApi;

    /**
     * 设置权限
     *
     * @param userId
     * @return
     */
    public Set<String> getAuthRoleAndResourceByUserId(String userId) {
        // 查询权限
        Set<String> resourcesCodeList = userApi.getResourcesCodeByUserId(userId);
        Set<String> roleKeyList = userApi.getAuthRoleKeyByUserId(userId);
        CollUtil.addAll(resourcesCodeList, roleKeyList);
        return resourcesCodeList;
    }


    @Override
    public void refreshUserInfoByUserId(String userId) {
        SaSession session = StpUtil.getSessionByLoginId(userId, false);
        if (session != null) {
            Set<String> authRoleAndResourceByUserId = getAuthRoleAndResourceByUserId(userId);
            LoginAccount loginOutputDTO = session.getModel(Constant.SESSION_USER_KEY, LoginAccount.class);
            loginOutputDTO.setResources(authRoleAndResourceByUserId);
            session.set(Constant.SESSION_USER_KEY, loginOutputDTO);
        }
    }
}
